package com.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.annotation.LoginFilter;
import com.demo.bean.DataTable;
import com.demo.bean.Ret;
import com.demo.util.JSONUtils;
import com.demo.validator.AdminLoginValidate;
import com.vsd.domain.User;
import com.vsd.domain.UserCreditLog;
import com.vsd.service.UserCreditLogService;
import com.vsd.service.UserService;

@Controller
@RequestMapping("/user")
@LoginFilter(validateClz=AdminLoginValidate.class)
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private UserCreditLogService userCreditLogService;
	
	@RequestMapping("/list")
	@ResponseBody
	public String storeList(HttpSession session,@RequestParam("draw") Integer draw
			,@RequestParam("start") Integer start,@RequestParam("length") Integer length
			,@RequestParam("search[value]") String search,HttpServletRequest request){
		
		Page<User> list = userService.findAll(new PageRequest(start/length, length,new Sort(Direction.DESC, "createTime")));
		
		return JSONUtils.serialize(new DataTable(draw+1,Integer.parseInt(list.getTotalElements()+""), list.getContent()));
	}
 
	
	@RequestMapping("/save")
	@ResponseBody
	public String save(String id,Integer enabled,HttpServletRequest request){
		User u = new User();
		u.setId(id);
		u.setEnabled(enabled);
		userService.updateByPrimaryKey(u);
		
		return JSONUtils.serialize(new Ret(0));
	}
	
	@RequestMapping("/findCreditLog")
	@ResponseBody
	public String findById(HttpSession session,@RequestParam("draw") Integer draw
			,@RequestParam("start") Integer start,@RequestParam("length") Integer length
			,@RequestParam("search[value]") String search,String userId,HttpServletRequest request){
		
		Page<UserCreditLog> list = userCreditLogService.findByUserId(userId, new PageRequest(start/length, length,new Sort(Direction.DESC, "createTime")));
		
		return JSONUtils.serialize(new DataTable(draw+1,Integer.parseInt(list.getTotalElements()+""), list.getContent()));
	}
 
}
